package gw

import (
	"gitee.com/deep-sea-tech/ds-go-client/dsregistry"
	"github.com/pkg/errors"
	"log"
	"net/http"
)

// 示例鉴权插件，只实现Before
type AuthPlugin struct{}

func (a *AuthPlugin) Before(w http.ResponseWriter, r *http.Request) error {
	token := r.Header.Get("Authorization")
	if token != "Bearer secrettoken" {
		http.Error(w, "Unauthorized", http.StatusUnauthorized)
		return errors.New("unauthorized")
	}
	return nil
}

func (a *AuthPlugin) After(w http.ResponseWriter, r *http.Request, resp *http.Response) error {
	// 不做任何处理
	return nil
}
func main() {
	registry := &dsregistry.RedisRegistry{}

	gw := NewGateway(registry)
	gw.AddRoute("/api/user", "user-service", []Plugin{&AuthPlugin{}})

	log.Println("Gateway listen on :8080")
	if err := http.ListenAndServe(":8080", gw); err != nil {
		log.Fatalf("Server error: %v", err)
	}
}
